#include <iostream>
#include <string>
#include <vector>
using namespace std;

vector<int> next(string pattern) {
    int n = pattern.size();
    vector<int> nxt(n);
    nxt[0] = 0;
    int j = 0;
    for (int i = 1; i < n; i++) {
        while (j > 0 && pattern[i] != pattern[j]) {
            j = nxt[j - 1];
        }

        if (pattern[i] == pattern[j]) {
            j++;
        }
        nxt[i] = j;
    }
    return nxt;
}

vector<int> nextval(string pattern) {
    vector<int> nxt = next(pattern);
    int n = nxt.size();
    vector<int> nxtval(n);
    nxtval[0] = 0;
    for (int i = 1; i < n; i++) {
        if (pattern[i] == pattern[nxt[i]]) {
            nxtval[i] = nxtval[nxt[i]];
        } else {
            nxtval[i] = nxt[i];
        }
    }
    return nxtval;
}

int kmp(string target, string pattern) {
    vector<int> nxt = next(pattern);
    int m = target.size(), n = pattern.size();
    int j = 0;
    for (int i = 0; i < m; i++) {
        while (j > 0 && target[i] != pattern[j]) {
            j = nxt[j - 1];
        }

        if (target[i] == pattern[j]) {
            j++;
        }

        if (j == n) {
            return i - j + 1;
        }
    }
    return -1;
}

int main() {
    string text = "ABCABCABAB";
    string pattern = "ABCAB";

    int pos = kmp(text, pattern);

    if (pos != -1) {
        cout << "Pattern found at position: " << pos << endl;
    } else {
        cout << "Pattern not found." << endl;
    }

    return 0;
}